# Encoding: UTF-8
require 'rubygems'
require 'mechanize'
require 'rest_client'
require 'json'

class PostsController < ApplicationController

  helper :profile
  before_filter :protect, :protect_blog
  # GET /posts
  # GET /posts.xml
  def index
    #Recheck implement paginate for Rails 3.1.3
    #@pages, @posts = paginate(@blog.posts)
    @posts = @blog.posts
    # Paginated Array

    @title = "Administración del Blog"
    respond_to do |format|
      format.html # index.rhtml
      format.xml { render :xml => @posts.to_xml }
    end
  end

  # GET /posts/1
  # GET /posts/1.xml
  def show
    @post = Post.find(params[:id])
    @title = @post.title
    respond_to do |format|
      format.html # show.html.erb
      format.xml { render :xml => @post.to_xml }
    end
  end

  # GET /posts/new
  def new
    @post = Post.new
    @title = "Nuevo post"
  end

  # GET /posts/1;edit
  def edit
    @post = Post.find(params[:id])
    @title = "Edit #{@post.title}"
  end

  # POST /posts
  # POST /posts.xml
  def create
    @post = Post.new(params[:post])
    @post.blog = @blog
    respond_to do |format|
      if @post.duplicate? or @blog.posts << @post
        flash[:notice] = 'El post fue creado satisfactoriamente .'
        # Use of middleware for post in Twitter Facebook and LinkedIn
        if params[:post][:remote_image_url]!=''
          @image=params[:post][:remote_image_url]
        elsif @post.image.present?
          @image=(@post.image.filename).to_s
          @post.image.present?
          @image='http://127.0.0.1:3000/uploads/post/image/'+(@post.id).to_s+'/'+@image
        end
        if (@image.present?)
          @middleware=RestClient.post('http://localhost/midsocial/g/public',
        {:fb_access_token=>session[:facebook_token],
          :tt_access_token=>session[:twitter_token], :tt_access_token_secret=>session[:twitter_secret],
          :li_access_token=>session[:linkedin_token], :li_access_token_secret=>session[:linkedin_secret],
          :message=>@post.body, :title=>@post.title,:picture=>@image} )
          @parsed_json = JSON.parse(@middleware)
          @post.facebook_id=@parsed_json['facebook']['id']
          @post.twitter_id=@parsed_json['twitter']['id']
          @post.linkedin_id=@parsed_json['linkedin']['id']
        @post.save
        end
        if (!@image.present?)
          @middleware=RestClient.post('http://127.0.0.1/midsocial/g/public',
        {:fb_access_token=>session[:facebook_token],
          :tt_access_token=>session[:twitter_token], :tt_access_token_secret=>session[:twitter_secret],
          :li_access_token=>session[:linkedin_token], :li_access_token_secret=>session[:linkedin_secret],
          :message=>@post.body, :title=>@post.title} )
          @parsed_json = JSON.parse(@middleware)
          @post.facebook_id=@parsed_json['facebook']['id']
          @post.twitter_id=@parsed_json['twitter']['id']
          @post.linkedin_id=@parsed_json['linkedin']['id']
        @post.save
        end

        format.html { redirect_to blog_post_url(:id => @post) }
        format.xml  { head :created, :location => blog_post_url(:id => @post) }
      else
        format.html { render :action => "new" }
        format.xml { render :xml => @post.errors.to_xml }
      end
    end
    logger.debug '===========MIDLEWARE POST CREATE==========='
    logger.debug @middleware
    logger.debug '============================================'
  end

  # PUT /posts/1
  # PUT /posts/1.xml
  def update
    @post = Post.find(params[:id])
    respond_to do |format|
      if @post.update_attributes(params[:post])
        flash[:notice] = 'Post was successfully updated.'
        format.html { redirect_to blog_post_url(:id => @post) }
        format.xml { head :ok }
      else
        format.html { render :action => "edit" }
        format.xml { render :xml => @post.errors.to_xml }
      end
    end
  end

  # DELETE /posts/1
  # DELETE /posts/1.xml
  def destroy
    @post = Post.find(params[:id])
    @middleware=RestClient.delete('http://127.0.0.1/midsocial/g/comment', :params=>{:fb_access_token=>session[:facebook_token],
          :tt_access_token=>session[:twitter_token], :tt_access_token_secret=>session[:twitter_secret],
          :facebook_id=>@post.facebook_id, :twitter_id=>@post.twitter_id})
    if @post.destroy
      respond_to do |format|
        format.html { redirect_to blog_posts_url }
        format.xml { head :ok }
      end
    end
    logger.debug '===========MIDLEWARE POST DESTROY==========='
    logger.debug @middleware
    logger.debug '============================================'
  end

  def favorite
    post_id=params[:post]
    @favorites=Favorite.find(:all, :conditions => ["post_id=? AND user_id=?",post_id,@blog.user_id])
    if @favorites.size==0
      @favorites=Favorite.new(:user_id=>@blog.user_id, :post_id=>post_id)
      @favorites.save
      @post=Post.find(post_id)
      @middleware=RestClient.post('http://127.0.0.1/midsocial/g/like-favorite',
        {:fb_access_token=>session[:facebook_token],
          :tt_access_token=>session[:twitter_token], :tt_access_token_secret=>session[:twitter_secret],
          :li_access_token=>session[:linkedin_token], :li_access_token_secret=>session[:linkedin_secret],
          :facebook_id=>@post.facebook_id, :twitter_id=>@post.twitter_id} )
      logger.debug '===========MIDLEWARE LIKE FAVORITE=========='
      logger.debug @middleware
      logger.debug '============================================'
    else
      @favorites=Favorite.find(@favorites[0][:id])
      @post_id=@favorites.post_id
      @favorites.destroy
      @post=Post.find(@post_id)
      @middleware=RestClient.delete('http://127.0.0.1/midsocial/g/like-favorite',:params=>
        {:fb_access_token=>session[:facebook_token],
          :tt_access_token=>session[:twitter_token], :tt_access_token_secret=>session[:twitter_secret],
          :li_access_token=>session[:linkedin_token], :li_access_token_secret=>session[:linkedin_secret],
          :facebook_id=>@post.facebook_id, :twitter_id=>@post.twitter_id})
      logger.debug '===========MIDLEWARE UNLIKED UNFAVORITE====='
      logger.debug @middleware
      logger.debug '============================================'
    end
    redirect_to hub_path
  end

  private

  # Ensure that user is blog owner, and create @blog.
  def protect_blog
    @blog = Blog.find(params[:blog_id])
    user = User.find(session[:user_id])
    unless @blog.user == user
      flash[:notice] = "Este no es su blog"
      redirect_to hub_url
    return false
    end
  end
end
